package com.mark.springsecurity.service.impl;

import com.mark.springsecurity.domain.SysUser;
import com.mark.springsecurity.exception.SysUserNotFountException;
import com.mark.springsecurity.exception.SysUserUsernameExistedException;
import com.mark.springsecurity.repository.SysUserRepository;
import com.mark.springsecurity.service.UserService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    private final SysUserRepository sysUserRepository;

    public UserServiceImpl(SysUserRepository sysUserRepository) {
        this.sysUserRepository = sysUserRepository;
    }

    @Override
    public void save(SysUser sysUser) {
        Optional<SysUser> optionalSysUser =
                sysUserRepository.findByUsernameAndEnabled(sysUser.getUsername(), Boolean.TRUE);
        if (optionalSysUser.isPresent()) throw new SysUserUsernameExistedException("用户名已存在");
        else sysUserRepository.save(sysUser);
    }

    @Override
    public Page<SysUser> findAll(Example<SysUser> example, Pageable pageable) {
        return sysUserRepository.findAll(example, pageable);
    }

    @Override
    public SysUser getOne(long id) {
        Optional<SysUser> optionalSysUser = sysUserRepository.findByIdAndEnabled(id, Boolean.TRUE);
        if (optionalSysUser.isPresent()) return optionalSysUser.get();
        else throw new SysUserNotFountException("找不到该用户");
    }

    @Override
    public void update(SysUser sysUser) {
        if (Boolean.TRUE.equals(userNameExisted(sysUser))) throw new SysUserUsernameExistedException("用户名已存在");
        else getOne(sysUser.getId()).update(sysUser);
    }

    public Boolean userNameExisted(SysUser sysUser) {
        Optional<SysUser> optionalSysUser = sysUserRepository.findByUsernameAndEnabled(sysUser.getUsername(), Boolean.TRUE);
        if (optionalSysUser.isPresent()) return Boolean.TRUE;
        else return Boolean.FALSE;
    }

    @Override
    public void delete(Long id) {
        getOne(id).remove();
    }
}
